/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import cart.ShoppingCart;
import cart.ShoppingCartItem;
import collection.Products;
import com.opensymphony.xwork2.ActionContext;
import dao.UserDAO;
import dto.Product;
import dto_pakinfo.Profile;
import dto_pakinfo.User;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import util.ServerValidation;
import util.StringUtil;
import util.XMLUtil;

/**
 *
 * @author duonghung1369
 */
public class CartController extends BaseController {

    private ShoppingCart cart;
    private ShoppingCartItem item;
    private int itemId;
    private InputStream inputStream;
    private Map session;
    private final String CART = "cart";
    private Product product;
    private UserDAO userDAO;
    private Profile profile;
    private Log log;
    private String cartXML;

    public CartController() {
        log = LogFactory.getLog(CartController.class);
        session = ActionContext.getContext().getSession();
    }

    public String add_cart() {
        try {
            session = ActionContext.getContext().getSession();
            Object obj = session.get(CART);
            if (obj != null) {
                cart = (ShoppingCart) obj;
            } else {
                cart = new ShoppingCart();
            }

            item = new ShoppingCartItem();
            item.setItem(product);
            cart.addToCart(item);

            // store cart to session
            session.put(CART, cart);



            inputStream = new ByteArrayInputStream(String.valueOf(cart.getNumber_of_items()).getBytes("UTF-8"));
            return SUCCESS;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CartController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return ERROR;
    }

    public String view_cart() {
        session = ActionContext.getContext().getSession();
        Object obj = session.get(CART);
        if (obj != null) {
            cart = (ShoppingCart) obj;
        } else {
            cart = new ShoppingCart();
        }
        return SUCCESS;
    }

    public String checkout() {
        if (ServerValidation.isGuest()) {
            session = ActionContext.getContext().getSession();
            session.put(StringUtil.CARTXML, cartXML);
            return LOGIN;
        } else if (ServerValidation.isAdmin()) {
            addActionError("Just registered user can do this function!");
            return StringUtil.INVALID_ROLE;
        } else {
            try {
                if (cartXML == null) {
                    cartXML = (String) session.get(StringUtil.CARTXML);
                }

                // .remove last ',' for no reason lol.
                cartXML = cartXML.trim();
                int index = cartXML.lastIndexOf(',');
                int length = cartXML.length();
                while (index == (length - 1)) {
                    cartXML = cartXML.substring(0, index);
                    cartXML = cartXML.trim();
                    index = cartXML.lastIndexOf(',');
                    length = cartXML.length();
                }

                System.out.println(cartXML + "  ++++++In check out");

                StringReader sr = new StringReader(cartXML.trim());
                JAXBContext context = JAXBContext.newInstance(Products.class);
                Object objClient = XMLUtil.unmarshalObject(context, sr);
                String filePath = System.getProperty("rootPath") + util.StringUtil.XML_FOLDER_PATH + "products.xml";
                Object objServer = XMLUtil.unmarshalObject(context, filePath);

                Products clientItems;
                Products serverItems;

                if (objClient != null && objServer != null) {
                    clientItems = (Products) objClient;
                    serverItems = (Products) objServer;

                    List<String> errors = ServerValidation.validateCheckoutProcesscing(clientItems, serverItems);

                    if (errors.size() > 0) {
                        for (String s : errors) {
                            addActionError(s);
                        }
                        return INPUT;
                    }
                }

                // get profile information and field value for check out information page.
                session = ActionContext.getContext().getSession();
                userDAO = new UserDAO(User.class);
                userDAO.openSession();
                User user = userDAO.get((Integer) session.get(StringUtil.USERID));
                Hibernate.initialize(user.getProfile());
                profile = user.getProfile();
                userDAO.closeSession();
                return SUCCESS;
            } catch (JAXBException ex) {
                log.error(ex);
                return ERROR;
            }
        }
    }

    public HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * @return the cart
     */
    public ShoppingCart getCart() {
        return cart;
    }

    /**
     * @param cart the cart to set
     */
    public void setCart(ShoppingCart cart) {
        this.cart = cart;
    }

    /**
     * @return the item
     */
    public ShoppingCartItem getItem() {
        return item;
    }

    /**
     * @param item the item to set
     */
    public void setItem(ShoppingCartItem item) {
        this.item = item;
    }

    /**
     * @return the itemId
     */
    public int getItemId() {
        return itemId;
    }

    /**
     * @param itemId the itemId to set
     */
    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    /**
     * @return the inputStream
     */
    public InputStream getInputStream() {
        return inputStream;
    }

    /**
     * @param inputStream the inputStream to set
     */
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * @return the product
     */
    public Product getProduct() {
        return product;
    }

    /**
     * @param product the product to set
     */
    public void setProduct(Product product) {
        this.product = product;
    }

    /**
     * @return the profile
     */
    public Profile getProfile() {
        return profile;
    }

    /**
     * @param profile the profile to set
     */
    public void setProfile(Profile profile) {
        this.profile = profile;
    }

    /**
     * @return the cartXML
     */
    public String getCartXML() {
        return cartXML;
    }

    /**
     * @param cartXML the cartXML to set
     */
    public void setCartXML(String cartXML) {
        this.cartXML = cartXML;
    }
}
